package kt.com.bilin.coin.ui.activity

import android.content.DialogInterface
import android.content.Intent
import android.os.Handler
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import com.bilin.coin.BuildConfig
import com.bilin.coin.R
import com.bilin.coin.bean.CommonSuccessEvent
import com.bilin.coin.bean.UpDateMsgBean
import com.bilin.coin.bean.WebUpDateUrlBackMsgBean
import com.bilin.coin.service.DownloadFileService
import com.bilin.coin.utils.MobilePhoneDeviceInfo
import com.bilin.coin.widget.OngoingUpdateDialog
import com.bilin.coin.widget.UpDateDialog
import com.flyco.tablayout.listener.OnTabSelectListener
import com.yanzhenjie.permission.runtime.Permission
import com.yanzhenjie.sofia.Utils
import kotlinx.android.synthetic.main.activity_v2_main.*
import kt.com.bilin.coin.ad.AdManager
import kt.com.bilin.coin.api.API_SERVICE
import kt.com.bilin.coin.api.ApiObserver
import kt.com.bilin.coin.api.toData
import kt.com.bilin.coin.common.ARouterNavigation
import kt.com.bilin.coin.common.permissionRequest
import kt.com.bilin.coin.common.tabData
import kt.com.bilin.coin.common.toastMessageLong
import kt.com.bilin.coin.ui.fragment.*
import kt.com.bilin.coin.utils.ActivityManger
import kt.com.bilin.coin.utils.FragmentChangeManager
import kt.com.bilin.coin.viewmodel.BackgroundCommonApi
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

class MainActivity : BaseActivity(R.layout.activity_v2_main), OnTabSelectListener {
    private var mFragmentChangeManager: FragmentChangeManager? = null
    private var mUpDateDialog: UpDateDialog? = null
    private var strLink: String? = null
    private var type = 0
    override fun initView() {
        ActivityManger.finishAllActivity(MainActivity::class.java)
        Utils.invasionStatusBar(this)
        Utils.setStatusBarDarkFont(this, false)
        permissionRequest {
            permission(Permission.WRITE_EXTERNAL_STORAGE)
            permission(Permission.READ_EXTERNAL_STORAGE)
        }
        tabLayout.tabData {
            tab("首页", R.mipmap.tab_home, R.mipmap.tab_home_gren)
            tab("游戏", R.mipmap.tab_game, R.mipmap.tab_game_gren)
            tab("福利", R.mipmap.tab_fuli, R.mipmap.tab_fuli_gren)
            tab("我的", R.mipmap.tab_mine, R.mipmap.tab_mine_gren)
        }
        tabLayout.setOnTabSelectListener(this)
        val fragments = ArrayList<Fragment>()
        fragments.add(HomeFragment())
        fragments.add(GameFragment())
        fragments.add(WelfareFragment())
        fragments.add(MyFragment())
        mFragmentChangeManager = FragmentChangeManager(supportFragmentManager, R.id.frameLayout, fragments)
    }

    override fun initData() {
        BackgroundCommonApi.notify()
        AdManager.init(this)
        launchUI({ API_SERVICE.version(MobilePhoneDeviceInfo.getVersionName(this@MainActivity)).toData() }, ApiObserver {
            it?.run {
                if (BuildConfig.DEBUG) {
                    status = 0
                }
                strLink = link
                when (status) {
                    0 -> {
                        //showToast("不需要更新");
                    }
                    1 -> {
                        type = status
                        mUpDateDialog = UpDateDialog(this@MainActivity, R.style.Dialog, false, newVersion, content, "main")
                        mUpDateDialog?.show()
                    }
                    2 -> {
                        type = status
                        mUpDateDialog = UpDateDialog(this@MainActivity, R.style.Dialog, true, newVersion, content, "main")
                        mUpDateDialog?.setOnKeyListener(keyListener)
                        mUpDateDialog?.setCancelable(false)
                        mUpDateDialog?.show()
                    }
                }
            }
        })
    }

    override fun onResume() {
        super.onResume()
        AdManager.showInner(this)
    }

    fun changeTab(position: Int) {
        onTabSelect(position)
        tabLayout.currentTab = position
    }

    override fun onTabSelect(position: Int) {
        mFragmentChangeManager?.setFragments(position)
        Utils.setStatusBarDarkFont(this, 1 == position || 2 == position)
    }

    override fun onTabReselect(position: Int) {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun WebUpDateUrlBackMsg(mWebUrlBackMsgBean: WebUpDateUrlBackMsgBean) {
//        val update = mWebUrlBackMsgBean.isUpdate
//        if (update) {
//            val url = mWebUrlBackMsgBean.url
//            if (type == 1) {
//                getString(R.string.start_download_ing).toastMessageLong()
//                val itDownloadFile = Intent(this@MainActivity, DownloadFileService::class.java)
//                itDownloadFile.putExtra("url", url)
//                startService(itDownloadFile)
//                mUpDateDialog?.dismiss()
//            } else {
//                mUpDateDialog?.dismiss()
//                val updateDialog = OngoingUpdateDialog(this@MainActivity, R.style.Dialog, url)
//                updateDialog.setCancelable(false)
//                updateDialog.show()
//            }
//        }
        EventBus.getDefault().removeStickyEvent(mWebUrlBackMsgBean)
    }

    /**
     * 更新的对话框回传
     *
     * @param upDateMsgBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun UpDateMsg(upDateMsgBean: UpDateMsgBean) {
        val isUpDateMsg = upDateMsgBean.ismUpDateMsg()
        val ismMianAndSet = upDateMsgBean.ismMianAndSet()
        if (ismMianAndSet) {
            if (isUpDateMsg) {
                permissionRequest {
                    permission(Permission.WRITE_EXTERNAL_STORAGE)
                    permission(Permission.READ_EXTERNAL_STORAGE)
                    onGranted {
                        ARouterNavigation("/common/WebLoadingUpdateActivity") {
                            withString("mMianAndSet", "main")
                            withString("strUrl", strLink)
                        }
                    }
                }
            } else {
                mUpDateDialog?.dismiss()
            }
        }
        EventBus.getDefault().removeStickyEvent(upDateMsgBean)
    }

    private val keyListener = DialogInterface.OnKeyListener { dialog, keyCode, event ->
        if (keyCode == KeyEvent.KEYCODE_BACK && event.repeatCount == 0) {
            if (mUpDateDialog?.isShowing == true) {
                mUpDateDialog?.dismiss()
            }
            finish()
            true
        } else {
            false
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun switchTab(switchTabEvent: CommonSuccessEvent) {
        if (switchTabEvent.type == CommonSuccessEvent.SwitchTab) {
            onTabSelect(0)
        }
        EventBus.getDefault().removeStickyEvent(switchTabEvent)
    }

    private var isKeycodeBack = true
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Handler().postDelayed({ isKeycodeBack = true }, 2000)
            if (isKeycodeBack) {
                "再按一次返回键退出应用".toastMessageLong()
                isKeycodeBack = false
            } else {
                finish()
            }
        }
        return true
    }

}